package com.njym.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.njym.annotation.PermInfo;
import com.njym.entity.ReconcileAbnormalRec;
import com.njym.entity.SysPaymentMode;
import com.njym.entity.SysUser;
import com.njym.payment.alipay.service.AliPayService;
import com.njym.payment.wxpay.service.WxService;
import com.njym.service.AbnormalOrderService;
import com.njym.service.PlatformBusinessRecService;
import com.njym.service.SysPaymentModeService;
import com.njym.tradeStatusConfig.AliTradeStatus;
import com.njym.tradeStatusConfig.WxTradeStatus;
import com.njym.util.PageUtils;
import com.njym.util.SNUtil;
import com.njym.vo.Json;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Created with IDEA
 * author:张善兵
 * Date:2018/8/23
 * Time:下午2:14
 */

@PermInfo(value = "异常订单接口")
@RestController
@RequiresPermissions("a:order:ab")
@RequestMapping("/abnormalorder")
public class AbnormalOrderController {
    @Autowired
    private AbnormalOrderService abnormalOrderService;

    @Autowired
    private SysPaymentModeService sysPaymentModeService;

    @Autowired
    PlatformBusinessRecService platformBusinessRecService;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private WxService wxService;

    private static final Logger log = LoggerFactory.getLogger(AbnormalOrderController.class);

    /**
     * method: queryPlatformBusinessRec
     *
     * @Description:
     * @param: [body]
     * @return: com.njym.vo.Json
     * @author: yh
     * @date: 2018/9/14 17:42
     */
    @PermInfo("搜索异常订单")
    @RequiresPermissions("a:order:ab:query")
    @PostMapping("/queryDetail")
    public Json queryAbnormalOrderDetail(@RequestBody String body) {
        String oper = "query queryAbnormalOrder info";
        log.info("{}, body: {}", oper, body);

        JSONObject json = JSON.parseObject(body);
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();
        String orgId = user.getOrgId();
        if (orgId.equals("0")) {
            orgId = null;
        }
        //交易 冲正记录，充值记录， 退款记录查询
        Integer recType = json.getInteger("recType");
        String modeId = json.getString("modeId");
        String channelId = json.getString("channelId");
        String outTradeNo = json.getString("outTradeNo");

        Object timeInterval = json.get("timeInterval");
        Date start = null;
        Date end = null;
        if (timeInterval != null && timeInterval.getClass() == JSONArray.class) {
            JSONArray timeIntervalarr = (JSONArray)timeInterval;
            start = timeIntervalarr.getTimestamp(0);
            end = timeIntervalarr.getTimestamp(1);
        }

        Page<ReconcileAbnormalRec> page = abnormalOrderService.queryAbnormalOrderDetail(PageUtils.getPageParam(json), orgId, modeId, channelId, recType, outTradeNo, start, end);
        return Json.succ(oper).data("page", page);
    }

    /**
     * 退款
     * @param body
     * @return
     */
    @PermInfo("搜索异常订单")
    @RequiresPermissions("a:order:ab:refund")
    @PostMapping("/refund")
    public Json refund(@RequestBody String body) {
        String oper = "refund";
        log.info("{}, body: {}", oper, body);
        JSONObject json = JSON.parseObject(body);
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();

        String id = json.getString("id");
        String orgId = json.getString("orgId");
        String modeId = json.getString("modeId");
        String outTradeNo = json.getString("outTradeNo");
        String refundFee = json.getString("refundFee");
        String channelId = json.getString("channelId");
        String refundReason = json.getString("refundReason");

        if (orgId == null || orgId.equals("")) {
            return Json.fail(oper, "orgId不能为空！");
        }
        if (modeId == null || modeId.equals("")) {
            return Json.fail(oper, "modeId不能为空！");
        }
        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        if (outTradeNo == null || outTradeNo.equals("")) {
            return Json.fail(oper, "outTradeNo不能为空！");
        }
        if (refundFee == null || refundFee.equals("")) {
            return Json.fail(oper, "refundFee不能为空！");
        }
        if (refundReason == null || refundReason.equals("")) {
            refundReason = "长款订单退款处理";
        }
        ReconcileAbnormalRec reconcileAbnormalRec = abnormalOrderService.selectById(id);
        SysPaymentMode sysPaymentMode = sysPaymentModeService.selectById(modeId);
        String result = "";
        boolean resultFlag = false;
        if (sysPaymentMode != null) {
            String modeCode = sysPaymentMode.getModeCode();
            switch (modeCode) {
                case "alipay":
                    String flag =  aliPayService.refund(orgId,outTradeNo,refundFee,refundReason,SNUtil.createSN3(),channelId,user.getUid(),user.getUname());
                    switch (flag){
                        case AliTradeStatus.TRADE_SUCCESS:
                            result = "退款成功";
                            resultFlag = true;
                            break;
                        case AliTradeStatus.QUERY_FAILURE:
                            result = "退款失败";
                            break;
                        default:
                            break;
                    }
                    break;
                case "wxpay":
                    String wxResult = wxService.refund(orgId, outTradeNo, SNUtil.createSN3(), refundFee, refundFee, refundReason,user.getUid(),user.getUname(),channelId);
                    if (wxResult.equals(WxTradeStatus.SUCCESS)) {
                        result = "退款成功";
                        resultFlag = true;
                    } else {
                        result = "退款失败";
                    }
                    break;
                default:
                    result = "支付方式不支持";
                    break;
            }
        } else {
            return Json.fail(oper, "支付方式不存在！");
        }
        if (resultFlag) {
            //更新异常记录
            reconcileAbnormalRec.setStatus(Byte.valueOf("2"));
            reconcileAbnormalRec.setOperatorId(user.getUid());
            reconcileAbnormalRec.setOperatorName(user.getUname());
            reconcileAbnormalRec.setUpdateDate(new Date());
            reconcileAbnormalRec.updateById();
        }
        return Json.succ(oper).data(result);
    }

}
